<?php
defined('_JEXEC') or die();

jimport('joomla.application.component.model');  

class WrdModelAtransaction extends WrdModel
{
    var $_data;
	var $_id;
	var $_total = null;
	var $_pagination = null;
	var $_limit = null;
	var $_limitstart = null;

	function __construct(){
		
		parent::__construct();
		$mainframe = &JFactory::getApplication();
		$context = JRequest::getCmd('option');
		$view = JRequest::getCmd('view');
		
		$this->_limit = $mainframe->getUserStateFromRequest( $context.$view.'limit', 'limit', $mainframe->getCfg('list_limit'), 0);
		$this->_limitstart = $mainframe->getUserStateFromRequest( $context.$view.'limitstart', 'limitstart', 0 );

		$this->setState('limit', $this->_limit);
		$this->setState('limitstart', $this->_limitstart);
	}

	function getData(){
		
		if (empty($this->_data)){
			$query = $this->_buildQuery();
			$this->_db->setQuery( $query, $this->_limitstart, $this->_limit );
			$this->_data = $this->_db->loadObjectList();
		}
		return $this->_data;
	}

	function getTotal(){
		if (empty($this->_total)){
			$query = $this->_buildQuery();
			$this->_total = $this->_getListCount($query);
		}
		return $this->_total;
	}

	function getPagination(){
		if (empty($this->_pagination))
		{
			jimport('joomla.html.pagination');
			$this->_pagination = new JPagination( $this->getTotal(), $this->_limitstart, $this->_limit );
		}
		return $this->_pagination;
	}

	function _buildQuery(){
		$mainframe = &JFactory::getApplication();
		$context = JRequest::getCmd('option');
		$view = JRequest::getCmd('view');

		$orderby 			= $this->_buildContentOrderBy();
		$search 			= $mainframe->getUserStateFromRequest( $context.$view.'search','search','','string');
		$filter_state 		= $mainframe->getUserStateFromRequest( $context.$view.'published','published',-1,'int');
		$filter_user 		= $mainframe->getUserStateFromRequest( $context.$view.'created_id','created_id',-1,'int');
		
		$search 			= JString::strtolower( $search );
		
		$where = array();

		if ( $search ){
			$where[] = 't.vip_number LIKE '.$this->_db->Quote( '%'.$this->_db->getEscaped( $search, true ).'%', false );
		}
		if ( $filter_user  != -1){
			$where[] = 't.created_id = '.$filter_user;
		}
		
		$where 		= ( count( $where ) ? ' WHERE ' . implode( ' AND ', $where ) : '' );
		$query = ' SELECT 
					t.id,
					t.transaction_id,
					t.vip_number,
					t.date_receipt,
					t.outlet,
					t.pax,
					t.food,
					t.beverage,
					t.liquor,
					t.other,
					t.discount,
					t.netsale,
					t.sc,
					t.vat,
					t.total,
					t.created_date,
					t.created_id,
					t.pay_type,
					t.convert
                	FROM #__wrd_transaction as t
                	'

		. $where
		. $orderby;
		//echo $query ;
		return $query;
	}

	function _buildContentOrderBy(){
		$mainframe = &JFactory::getApplication();
		$context = JRequest::getCmd('option');
		$view = JRequest::getCmd('view');

		$filter_order     = $mainframe->getUserStateFromRequest( $context.$view.'filter_order_author','filter_order','id' );
		$filter_order_Dir = $mainframe->getUserStateFromRequest( $context.$view.'filter_order_Dir',  'filter_order_Dir', 'DESC' );
		$orderby 	= ' ORDER BY '.$filter_order.' '.$filter_order_Dir;
		return $orderby;
	}
    
	function delete($cid = array()){
		$result = false;

		if (count( $cid )){
			JArrayHelper::toInteger($cid);
			$cids = implode( ',', $cid );
			$query = 'DELETE FROM #__wrd_transaction'
				. ' WHERE id IN ( '.$cids.' )';
			$this->_db->setQuery( $query );
			if(!$this->_db->query()) {
				$this->setError($this->_db->getErrorMsg());
				return false;
			}
		}

		return true;
	}
 
	function publish($cid = array(), $publish = 1){
		$user 	=& JFactory::getUser();

		if (count( $cid ))
		{
			JArrayHelper::toInteger($cid);
			$cids = implode( ',', $cid );

			$query = 'UPDATE #__wrd_transaction'
				. ' SET published = '.(int) $publish
				. ' WHERE id IN ( '.$cids.' )'
			;
			$this->_db->setQuery( $query );
			if (!$this->_db->query()) {
				$this->setError($this->_db->getErrorMsg());
				return false;
			}
		}

		return true;
	}
    
     //save to table $nametable
    function store($post,$tablename){
		$post['date_receipt'] = $post['date_receipt']." ".$post['hour'].":".$post['minute'];
        $profile = JTable::getInstance($tablename, 'TableWrd');
        $profile->load();
        $profile->bind($post);
		//echo "<pre>";print_r($profile);exit;
		if ($profile->store()) {
			self::createPoint($profile);
			return $profile->id;
		} else {
			return 0;
		}
  	}
    
    
    private function createPoint($transaction){
        $user = JFactory::getUser();
		$moneyForOnePoint = PointProvider::getConfigByName($this->_db, 'money_for_one_point');
        $moneyForOnePoint = ($moneyForOnePoint > 0 ? $moneyForOnePoint : 50000);
		$defaultPointPerMoney  = PointProvider::getConfigByName($this->_db, 'default_point_per_money');
        $defaultPointPerMoney = ($defaultPointPerMoney > 0 ? $defaultPointPerMoney : 100);

		$db = JFactory::getDbo();
		$query = 'SELECT id,food,beverage,other,netsale,discount,date_receipt 
				FROM #__wrd_transaction 
				WHERE id='.$transaction->id;

		$db->setQuery($query);
		$item = $db->loadObject();
		$point = WrdHelper::machPoint($transaction->id,'transaction');

		if($point->point == 0 || $point->point == ''){
			$point->point = $defaultPointPerMoney;
		}

		if(($point->f==0)&&($point->b==0)&&($point->o==1))
			$p = intval(($item->other) / $moneyForOnePoint) * $point->point;
		else if(($point->f==0)&&($point->b==1)&&($point->o==0))
			$p = intval(($item->beverage) / $moneyForOnePoint) * $point->point;
		else if(($point->f==0)&&($point->b==1)&&($point->o==1))
			$p = intval(($item->beverage+$item->other) / $moneyForOnePoint) * $point->point;
		else if(($point->f==1)&&($point->b==0)&&($point->o==0))
			$p = intval($item->food / $moneyForOnePoint) * $point->point;
		else if(($point->f==1)&&($point->b==0)&&($point->o==1))
			$p = intval(($item->food+$item->other) / $moneyForOnePoint) * $point->point;
		else if(($point->f==1)&&($point->b==1)&&($point->o==0))
			$p = intval(($item->food+$item->beverage) / $moneyForOnePoint) * $point->point;
		else $p = intval(($item->netsale) / $moneyForOnePoint) * $point->point;
		
		$expire  = WrdHelper::calculateExpiredDate($transaction->date_receipt);
		if($expire != '0000-00-00'){
			if(strtotime($expire.' 23:59:59') < time())
				$expired = 1;
			else
				$expired = 0;
		}
		else
			$expired = 0;
         //insert point table
        $obj = new stdClass;
        $obj->id = null;
        $obj->user_id = $point->user_id;
        $obj->transaction = $transaction->transaction_id;
        $obj->point = $p ;
        $obj->expire = $expire;
        $obj->expired = $expired;
        $obj->outlet = $transaction->outlet;
        $obj->des = 'transaction';
        $obj->type = 0;
        $obj->created_id = $user->id;
        $obj->created_date = $transaction->date_receipt;
        $obj->modify_id = '' ;
        $obj->modify_date = '' ;
        $this->_db->insertObject('#__wrd_point', $obj);
        
        
		
		// Tinh lai point summary cho user 
		$month = date('m',strtotime($obj->created_date));
		$year = date('Y',strtotime($obj->created_date));
		
		if($year < date('Y')||(($year == date('Y'))&&($month <= date('m')))){
			
			while(($month != date('m'))||($year != date('Y'))){
				WrdHelper::updateSummaryPoint($obj->user_id,$year,$month);
				if($month+1 <=12) ++$month;
				else {$month = 1;++$year;}
			}	
		}
		WrdHelper::updateSummaryPoint($obj->user_id,date('Y'),date('m'));
		$p_o_u = WrdHelper::getPoints($obj->user_id);
		$sql = 'UPDATE #__wrd_profile SET p_o_u = '.$p_o_u->point .',point_life_time = '.$p_o_u->point_life_time.' WHERE user_id = '.$obj->user_id;
		$db->setQuery($sql);
		$db->query();
    }
  	
  	function getList(){
  		$query = 'SELECT id AS value, name AS text FROM #__wrd_transaction WHERE published=1';

		$this->_db->setQuery( $query );
		return $this->_db->loadObjectList();
  	}

	function getUserList(){

		$query = 'SELECT a.created_id as value , b.username as text FROM #__wrd_transaction a LEFT JOIN #__users b ON a.created_id = b.id 
			GROUP BY a.created_id';
		
		$this->_db->setQuery( $query );
		return $this->_db->loadObjectList();
	}
  	
  	function getItem($id,$type = 'id'){
  		
  		if($type == 'id'){
  			$query = 'SELECT * FROM #__wrd_transaction WHERE id = '.$id;
			$this->_db->setQuery($query);
  		}
  		else{
  			$query = 'SELECT * FROM #__wrd_transaction WHERE transaction_id = '.$id;
  			$this->_db->setQuery($query);
  		}
  		
		return $this->_db->loadObject();
  	}
  	
	function saveorder($pks = null, $order = null,$tablename)
	{
		//Initialise variables.
		
		$table 	= JTable::getInstance($tablename, 'TableWrd');
		$conditions	= array();

		if (empty($pks)) {
			return JError::raiseWarning(500, JText::_($this->text_prefix.'_ERROR_NO_ITEMS_SELECTED'));
		}

		// update ordering values
		foreach ($pks as $i => $pk) {
			$table->load((int) $pk);

			if ($table->ordering != $order[$i]) {
				$table->ordering = $order[$i];

				if (!$table->store()) {
					$this->setError($table->getError());
					return false;
				}

				// Remember to reorder within position and client_id
				$found = false;

				foreach ($conditions as $cond) {
					if ($cond[1] == $condition) {
						$found = true;
						break;
					}
				}

				if (!$found) {
					$key = $table->getKeyName();
					$conditions[] = array ($table->$key, $condition);
				}
			}
		}

		foreach ($conditions as $cond) {
			$table->load($cond[0]);
			$table->reorder($cond[1]);
		}
		
		$this->cleanCache();
		return true;
	}
	
	public function reorder($pks, $delta = 0,$tablename){
		// Initialise variables.
		$table 	= JTable::getInstance($tablename, 'TableWrd');
		$pks	= (array) $pks;
		$result	= true;
		
		foreach ($pks as $i => $pk) {
			$table->reset();

			if ($table->load($pk)) {
				$where = array();
				if (!$table->move($delta, $where)) {
					$this->setError($table->getError());
					unset($pks[$i]);
					$result = false;
				}
			} else {
				$this->setError($table->getError());
				unset($pks[$i]);
				$result = false;
			}
		}

		if (empty($pks)) {
			$result = null;
		}

		if ($result == true) {
			$this->cleanCache();
		}

		return $result;
	}
}